import { Drawer, Form, Button, Row, Col, Input, Select, DatePicker, Divider, Modal, message, Table} from "antd";
import React from "react";
import DetailList from "./detailList";
import { businessTypeList, chargingAdd, chargingDetailPackageList, chargingInfo, chargingUpdate, combinationList, packageList } from "@/services/chargingManage";
import moment from "moment";
import { formatMessage } from 'umi-plugin-react/locale';

class CaseModal extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      visible:false,
      id:null,
      signList:[],
      packageList:[],
      signPrice:"",
      detail:{},
      useList:[],
      settlementList:[],
      readonly:false,
      list:[],
      total:0,
      current:1,
      size:3
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  initModal = data => {
    this.setState({
      visible:true,
      id:data?.id,
      readonly:data?.isLock == 1
    },() => {
      this.getBusinessTypeList()
      if(data){
        this.getDetail()
      }
      setTimeout(() => {
        this.DetailList.getList()
      },100)
    })
  }

  getBusinessTypeList = async () => {
    const res = await businessTypeList()
    this.setState({
      signList:res.sign.sort((a, b) => b.id - a.id),
      useList:res.use.sort((a, b) => b.id - a.id),
      settlementList:res.settlement.sort((a, b) => b.id - a.id)
    })
  }

  getDetail = async () => {
    const { id,current,size } = this.state;
    const res = await chargingInfo({id})
    const res2 = await chargingDetailPackageList({current,size,planId:id})
    let fields = [
      "name",
      "suggestionId",
      "signId",
      "signDate",
      "paymentProvision",
      "paidConsultant",
    ]
    let obj = {}
    for(const item of fields){
      if(item == 'signDate'){
        obj[item] = res[item] ? moment(res[item]) : null
      }else{
        obj[item] = res[item]
      }
    }
    this.props.form.setFieldsValue(obj)
    this.setState({
      detail:res,
      list:[
        ...res2.records,
        {
          packagePrice:'套餐总价：'+res.packageAllPrice,
          discountName:'综合折扣率：'+res.discountRate+'%',
          realPrice:'签约总额：'+res.realAllPrice,
          id:'1'
        }],
      total:res2.total + 1
    })
  }

  onClose = () => {
    this.setState({
      visible:false,
      id:null,
      signList:[],
      packageList:[],
      signPrice:"",
      detail:{},
      useList:[],
      settlementList:[],
      readonly:false,
      list:[],
      total:0,
      current:1,
      size:3
    })
  }

  okValidate = () => {
    this.props.form.validateFields((error,values) => {
      if(!error){
        this.doSave(values)
      }
    })
  }

  doSave = async values => {
    let res = {}
    if(this.state.id){
      values.id = this.state.id
      res = await chargingUpdate(values)
    }else{
      res = await chargingAdd(values)
    }
    if(res.code == -1){
      return false
    }
    let id = res.data && typeof(res.data) == 'string' ? res.data : this.state.id
    this.setState({ id },() => {
      this.getDetail()
    })
    
    message.info(res.message)
    this.props.refreshList()
  }

  renderName = (packageId,type) => {
    const { packageList } = this.state;
    let index = packageList.findIndex(item => item.id == packageId)
    return index != -1 ? type == 1 ? packageList[index].preview : packageList[index].name : ''
  }

  doSearch = (current) => {
    this.setState({current},() => {
      this.getDetail()
    })
  }

  render(){
    const { visible,signList,id,packageList,detail,useList,settlementList,readonly,list,current,size,total } = this.state
    const { form:{getFieldDecorator,getFieldValue} } = this.props;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const columns = [
      {
         title:formatMessage({ id: 'chargingCase.caseModal.detailName' }),
        dataIndex:"name",
        width:120
      },
      {
       title:formatMessage({ id: 'chargingCase.caseModal.packageType' }),
        dataIndex:"packageType",
        width:100,
        render:type => {
          return type == 0 ? '单套餐' : type == 1 ? '套餐组' : ''
        }
      },
      {
        title:formatMessage({ id: 'chargingCase.caseModal.usedPackage' }),
        dataIndex:"packageName",
        width:120
      },
      {
        title:formatMessage({ id: 'chargingCase.caseModal.packageStandardPrice' }),
        dataIndex:"packagePrice",
        width:100
      },
      {
        title:formatMessage({ id: 'chargingCase.caseModal.discountPlan' }),
        dataIndex:"discountName",
        width:120
      },
      {
        title:formatMessage({ id: 'chargingCase.caseModal.signAmount' }),
        dataIndex:"realPrice",
        width:100
      },
    ]
    return (
      <Drawer
         title={formatMessage({ id: 'chargingCase.caseModal.title' })}
        visible={visible}
        onClose={this.onClose}
        width={'100%'}
        destroyOnClose
      >
        <div style={{maxHeight:360,overflowY:"auto"}}>
          <h3>{formatMessage({ id: 'chargingCase.caseModal.basicInfo' })}</h3>
          <Form {...formItemLayout} className="normalForm">
            <div style={{display:"flex",alignItems:"stretch"}}>
              <div style={{width:'25%'}}>
                <Form.Item label={formatMessage({ id: 'chargingCase.caseModal.planName' })}>
                  {getFieldDecorator("name",{rules:[{required:true,message:formatMessage({ id: 'common.pleaseInput' })}]})(
                    <Input disabled={readonly} />
                  )}
                </Form.Item>
                <Form.Item label={formatMessage({ id: 'chargingCase.caseModal.paymentTerms' })}>
                  {getFieldDecorator("paymentProvision")(
                    <Input disabled={readonly} />
                  )}
                </Form.Item>
              </div>
              <div style={{width:'20%'}}>
                <Form.Item label={formatMessage({ id: 'chargingCase.caseModal.signParty' })}>
                  {getFieldDecorator("signId",{rules:[{required:true,message:formatMessage({ id: 'common.pleaseInput' })}]})(
                    <Select showSearch optionFilterProp="children" disabled={readonly}>
                      {signList.map(item => <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>)}
                    </Select>
                  )}
                </Form.Item>
                <Form.Item label={formatMessage({ id: 'chargingCase.caseModal.suggestion' })}>
                  {getFieldDecorator("suggestionId")(
                    <Input disabled={readonly} />
                  )}
                </Form.Item>       
              </div>
              <div style={{width:'20%'}}>
                <Form.Item label={formatMessage({ id: 'chargingCase.caseModal.signDate' })}>
                  {getFieldDecorator("signDate")(
                    <DatePicker disabled={readonly} />
                  )}
                </Form.Item>
                <Form.Item label=" " colon={false}>
                  <Button style={{marginRight:10}} onClick={this.onClose}>{formatMessage({ id: 'common.cancel' })}</Button>
                  {
                    readonly ? '' : <Button type="primary" onClick={this.okValidate}>{formatMessage({ id: 'common.save' })}</Button>
                  }
                </Form.Item>
              </div>
              <div style={{width:'30%'}}>
                  <Form.Item label={formatMessage({ id: 'chargingCase.caseModal.consultant' })}>
                  {getFieldDecorator("paidConsultant")(
                    <Input disabled={readonly} />
                  )}
                </Form.Item>
              </div>
              
            </div>
          </Form>
          <div>
            <Table 
              columns={columns}
              dataSource={list}
              rowKey={'id'}
              scroll={{x:"auto"}}
              pagination={{
                current,
                pageSize:size + 1,
                onChange:this.doSearch,
                total
              }}
            />
          </div>
        </div>

        <Divider style={{marginTop:0}} />

        <DetailList 
          onRef={ref => this.DetailList = ref} 
          caseId={id} 
          caseInfo={detail} 
          refreshCaseInfo={this.getDetail} 
          useList={useList}
          settlementList={settlementList}
          readonly={readonly}
        />

      </Drawer>
    )
  }
}

export default Form.create()(CaseModal)